# Copyright 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


# TODO(epg): No --with-revprop support here; see gvn change.


import gvn.changebranch
import gvn.cmdline
import gvn.errors


helptext__gvn_submit = """submit: Submit a changebranch to the source branch.
usage: submit -c CHANGE
"""


def Handle_GvnSubmit(ctx):
  (unused_username, change_name,
   unused_revision) = gvn.util.ParseChangeName(ctx.options.change)
  for path in ctx.wc.change_state[change_name].paths:
    if not gvn.util.IsChild(path, ctx.path_dir):
      raise gvn.errors.ChangeBranchOutsideTarget(path, ctx.path_dir)

  if ctx.options.with_revprop is not None:
    # TODO(epg): Support more than one --with-revprop.
    split = ctx.options.with_revprop.split('=', 1)
    if len(split) == 1:
      value = ''
    else:
      value = split[1]
    revprops = {split[0]: value}
  else:
    revprops = None

  cb = gvn.changebranch.ChangeBranch(ctx.config, ctx.project,
                                     change_name)
  try:
    cb.Submit(ctx.wc, revprops=revprops, pool=ctx.pool)
  except gvn.errors.Conflict, e:
    # TODO(epg): This isn't quit the right way to make the path in the
    # error message display-ready.  Maybe gvn.errors.Root should have
    # a DisplayString method or something that takes as an argument a
    # function(path) => display path.  gvn.cmdline.main would use
    # e.DisplayString(ctx.DisplayPath) instead of str(e).  In other
    # words, each subcommand shouldn't have to handle this on its own,
    # for each kind of error.
    e.path = ctx.DisplayPath(e.path)
    raise

  return 0


gvn.cmdline.AddCommand('submit', Handle_GvnSubmit, helptext__gvn_submit,
                       gvn.cmdline.AuthOptions(['change', 'with-revprop']),
                       {'change': 'changebranch ARG'})
